package mm.chenchen.modules.script.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import mm.chenchen.common.utils.MinioClientUtil;
import mm.chenchen.common.utils.MinioUtil;
import mm.chenchen.constant.ResultMsg;
import mm.chenchen.modules.file.service.impl.FileService;
import mm.chenchen.modules.script.dao.ScriptRunHisDao;
import mm.chenchen.modules.script.dao.model.request.ScriptRunHisQuery;
import mm.chenchen.modules.script.entity.ScriptRunHis;
import mm.chenchen.modules.script.service.ScriptRunHisService;
import mm.chenchen.utils.PageModel;
import mm.chenchen.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Service("scriptRunHisService")
////@DataSource("爬虫资源库")
public class ScriptRunHisServiceImpl extends ServiceImpl<ScriptRunHisDao, ScriptRunHis> implements ScriptRunHisService {
    @Autowired
    private MinioClientUtil minioClientUtil;
    @Autowired
    private FileService fileService;

    public R findPage(Page<Map> page, ScriptRunHisQuery param) {
        IPage<ScriptRunHis> pageData = baseMapper.findPage(page, param);
        if (pageData != null) {
            return R.ok().setData(new PageModel(pageData.getRecords(),pageData.getTotal(),pageData.getSize(),pageData.getCurrent()));
        } else {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
    }

    public R getById(Long id){
        return R.ok().setData(super.getById(id));
    };

    public R saveInfo(ScriptRunHis param){
        return R.ok().setData(super.save(param));
    };

    public R update(ScriptRunHis param){
            ScriptRunHis data=super.getById(param.getId());
            if(ObjectUtils.isEmpty(data)){
                return R.error(ResultMsg.DATA_NOT_EXIT);
            }
        return R.ok().setData(super.updateById(param));
    };

    public R deleteById(Long id){
        ScriptRunHis his=super.getById(id);
        MinioUtil.delete(minioClientUtil.getMinioClient(), "log",his.getLogAddr());
        return R.ok().setData(super.removeById(id));
    };
    public void downLoadFromMinio(Long id, HttpServletResponse response){
        ScriptRunHis his=super.getById(id);
        fileService.downLoadFromMinio("log",his.getLogAddr(),0l,response);
    }
}